import { Toast } from 'vant'
import { getCookie } from '.././../cookies'
export default {
  namespaced: true,
  state: {
    title: 'goods',
    count: 5,
    cart: JSON.parse(localStorage.carts || ' []')
  },
  mutations: {
    ADD_CART(state, payload) {
      if (getCookie('user')) {
        let flag = false
        state.cart.forEach(item => {
          if (item.id === payload.id) {
            flag = true
            item.count += payload.count
          }
        })
        if (!flag) {
          state.cart.push(payload)
        }
        // console.log(state.cart)
        localStorage.carts = JSON.stringify(state.cart)
        // console.log(JSON.parse(localStorage.carts))
      } else {
        Toast('请先登录账号吧')
        // 待优化 vuex内实现路由跳转
        // location.href = '/login'
        // this.router.push('/login')
      }
    }
  },
  actions: {
    addCart({ commit }, obj) {
      commit('ADD_CART', obj)
    }
  }
}